package dsk.demo.miaosha.demo.controller;


import dsk.demo.miaosha.demo.pojo.User;
import dsk.demo.miaosha.demo.service.IGoodsService;
import dsk.demo.miaosha.demo.service.IUserService;
import dsk.demo.miaosha.demo.service.impl.UserServiceImpl;
import dsk.demo.miaosha.demo.vo.GoodsDetailVo;
import dsk.demo.miaosha.demo.vo.GoodsVo;
import dsk.demo.miaosha.demo.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {

    @Autowired
    IUserService userService;

    @Autowired
    IGoodsService goodsService;

    @RequestMapping("/toList")
    public String toGoods(Model model, User user) {
        log.info("request into toGoods");
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        return "goodsList";
    }

    @RequestMapping("/detail/{goodsId}")
    @ResponseBody
    public RespBean toDetail(@PathVariable Long goodsId, User user) {
        GoodsVo goods = goodsService.findGoodsVoById(goodsId);
        //处理秒杀倒计时
        Date startDate = goods.getStartDate();
        Date endDate = goods.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        if(nowDate.before(startDate)) {//秒杀开始前
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime())/1000);
        } else if (nowDate.after(endDate)) {//秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {//秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setUser(user);
        goodsDetailVo.setGoods(goods);
        goodsDetailVo.setRemainSeconds(remainSeconds);
        goodsDetailVo.setSecKillStatus(secKillStatus);
        return RespBean.success(goodsDetailVo);
    }


}
